package com.gitee.cc.system.realm;

import com.gitee.cc.system.domain.User;
import com.gitee.cc.system.service.LoginService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;

/**
 * @author : cc
 * @date : Create in 16:56 2018/7/28
 */
@Slf4j
public class UserRealm extends AuthorizingRealm {
    @Resource
    private LoginService loginService;
    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 登录
     *
     * @param
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();
        String password = "";
        if (upToken.getPassword() != null) {
            password = new String(upToken.getPassword());
        }
        User user = null;
        try {
            user = loginService.login(username, password);
        } catch (Exception e) {
            log.error("对用户[" + username + "]进行登录验证..验证未通过{}", e.getMessage());
            throw new AuthenticationException(e.getMessage(), e);
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, getName());
        //TODO 用户要做跨域处理
//        SecurityUtils.getSubject().getSession().setAttribute(Constants.SESSION_USER_INFO, user);
//        System.out.println(SecurityUtils.getSubject().getSession().getId());
        return info;
    }

}
